package model

import (
	"ginblog/utils/errmsg"
	"github.com/jinzhu/gorm"
)

type Category struct {
	ID   int    `json:"id"`
	Name string `json:"name"`
}

//验证分类是否存在
func CheckCategory(name string) int {
	var model Category
	db.Select("id").Where("name", name).First(&model)
	if model.ID > 0 {
		return errmsg.ErrorCategoryNotExist
	}
	return errmsg.SUCCESS
}

//新增分类
func AddCategory(model *Category) int {
	err = db.Create(&model).Error
	if err != nil {
		return errmsg.ERROR
	}
	return errmsg.SUCCESS
}

//查询分类
func GetCategory(name string) (*Category, int) {
	var model Category
	err = db.Where("name = ?", name).First(&model).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, errmsg.ERROR
	}
	return &model, errmsg.SUCCESS
}

//查询分类列表
func GetCategorys(page int, pageSize int) ([]Category, int) {
	var models []Category
	var total int

	err = db.Limit(pageSize).Offset((page - 1) * pageSize).Find(&models).Count(&total).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, 0
	}
	return models, total
}

//编辑分类
func EditCategory(id int, data *Category) int {
	var model Category
	var maps = make(map[string]interface{})
	maps["name"] = data.Name
	err = db.Model(&model).Where("id = ?", id).Update(maps).Error

	if err != nil {
		return errmsg.ERROR
	}
	return errmsg.SUCCESS
}

//删除分类
func DeleteCategory(id int) int {
	var model Category
	err = db.Where("id = ?", id).Delete(&model).Error //软删除
	//err = db.Where("id = ?", id).Unscoped().Delete(&model).Error //删除
	if err != nil {
		return errmsg.ERROR
	}
	return errmsg.SUCCESS
}
